﻿using System;
using Iworld.Client.Framework.AuthorService;
using Iworld.Client.Framework.GameService;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Collections.ObjectModel;
using System.Linq;
using Iworld.ViewModel;
using System.Windows.Controls.Primitives;
namespace Iworld.Client.Framework
{
    /// <summary>
    /// 游戏界面视图模型
    /// </summary>
    public class GameViewModel : MainFrameViewModelBase
    {

        #region 私有变量
        
        GameServiceClient gameClient = new GameServiceClient();
        AuthorServiceClient authorClient = new AuthorServiceClient();
        ImageSource currentShowImg;
        double currentBettingSpade = 0;
        double currentBettingHeart = 0;
        double currentBettingClub = 0;
        double currentBettingDiamond = 0;
        double currentBettingKing = 0;
        int currentChapterCountOfSpade = 0;
        int currentChapterCountOfHeart = 0;
        int currentChapterCountOfClub = 0;
        int currentChapterCountOfDiamond = 0;
        int currentChapterCountOfKing = 0;
        string timeDisplay = "";

        int? currentChapterNumber;
        int? currentRoundNumber;
        int? nextRoundNumber;
        DateTime? nextLotteryTime;

        /// <summary>
        /// 当前用户余额
        /// </summary>
        double golds;
        string goldsDisplay;

        double bettingUnit = 100;
        int minBettingSpan = 250;
        int submitBettingSpan = 2;
        bool isNeedSubmitBetting = false;

        bool autoBettingSpade = false;
        bool autoBettingHeart = false;
        bool autoBettingClub = false;
        bool autoBettingDiamond = false;
        bool autoBettingKing = false;
        ObservableCollection<GameRoundInfo> gameRoundInfos;
        ObservableCollection<CurrentBettingUserInfo> currentBettingUserInfos;

        int? nextLeftTime = 0;

        double maxBetting = 9900;
        /// <summary>
        /// 最新的游戏信息
        /// </summary>
        GameChapterExport latestGameInfo;
        /// <summary>
        /// 定时按需要提交投注信息
        /// </summary>
        Storyboard sbBetting;
        /// <summary>
        /// 设置停止投注标记
        /// </summary>
        Storyboard sbStopBetting;
        /// <summary>
        /// 主要循环线程
        /// </summary>
        Storyboard sbTime;

        /// <summary>
        /// 自动压分处理线程
        /// </summary>
        Storyboard autoBetting;
        #endregion

        #region 公开属性

        /// <summary>
        /// 当前实时用户投注信息
        /// </summary>
        public ObservableCollection<CurrentBettingUserInfo> CurrentBettingUserInfos
        {
            set
            {
                if (value != currentBettingUserInfos)
                {
                    currentBettingUserInfos = value;
                    this.OnPropertyChanged("CurrentBettingUserInfos");
                }
            }
            get
            {
                return currentBettingUserInfos;
            }

        }

        /// <summary>
        /// 用户当前的余额
        /// </summary>
        public double Golds
        {
            set
            {
                if (value != golds)
                {
                    golds = value;
                    this.OnPropertyChanged("Golds");
                }
            }
            get
            {
                return golds;
            }
        }

        /// <summary>
        /// 当前余额显示内容
        /// </summary>
        public string GoldsDisplay
        {
            set
            {
                if (value != goldsDisplay)
                {
                    goldsDisplay = value;
                    this.OnPropertyChanged("GoldsDisplay");
                }
            }
            get
            {
                return goldsDisplay;
            }

        }

        /// <summary>
        /// 开奖时间提示显示内容
        /// </summary>
        public string TimeDisplay
        {
            set
            {
                if (value != timeDisplay)
                {
                    timeDisplay = value;
                    this.OnPropertyChanged("TimeDisplay");
                }
            }
            get
            {
                return timeDisplay;
            }
        }

        /// <summary>
        /// 当前轮号
        /// </summary>
        public int? CurrentChapterNumber
        {
            set
            {
                if (value != currentChapterNumber)
                {
                    currentChapterNumber = value;
                    this.OnPropertyChanged("CurrentChapterNumber");
                }
            }
            get
            {
                return currentChapterNumber;
            }
        }
     
        /// <summary>
        /// 当前局号
        /// </summary>
        public int? CurrentRoundNumber 
        {
            set
            {
                if (value != currentRoundNumber)
                {
                    currentRoundNumber = value;
                    this.OnPropertyChanged("CurrentRoundNumber");
                }
            }
            get
            {
                return currentRoundNumber;
            }
        }

        /// <summary>
        /// 下局局号
        /// </summary>
        public int? NextRoundNumber
        {
            set
            {
                if (value != nextRoundNumber)
                {
                    nextRoundNumber = value;
                    this.OnPropertyChanged("NextRoundNumber");
                }
            }
            get
            {
                return nextRoundNumber;
            }
        }

        /// <summary>
        /// 下期开奖时间
        /// </summary>
        public DateTime? NextLotteryTime
        {
            set
            {
                if (value != nextLotteryTime)
                {
                    nextLotteryTime = value;
                    this.OnPropertyChanged("NextLotteryTime");
                }
            }
            get
            {
                return nextLotteryTime;
            }
        }

        /// <summary>
        /// 当前显示的大图片
        /// </summary>
        public ImageSource CurrrentShowImg 
        {
            set 
            {
                if (value != currentShowImg)
                {
                    currentShowImg = value;
                    this.OnPropertyChanged("CurrrentShowImg");
                }
            }
            get
            {
                return currentShowImg;
            }
        }

        /// <summary>
        /// 每次上分的量
        /// </summary>
        public double BettingUnit
        {
            set
            {
                if (value != bettingUnit)
                {
                    bettingUnit = value;
                    this.OnPropertyChanged("BettingUnit");
                }
            }
            get
            {
                return bettingUnit;
            }

        }

        /// <summary>
        /// 每次上分之间的最少间隔
        /// </summary>
        public int MinBettingSpan
        {
            set
            {
                if (value != minBettingSpan)
                {
                    minBettingSpan = value;
                    this.OnPropertyChanged("MinBettingSpan");
                }
            }
            get
            {
                return minBettingSpan;
            }

        }

        /// <summary>
        /// 当前的黑桃投注量
        /// </summary>
        public double CurrentBettingSpade 
        { 
            set
            {
                if(value != currentBettingSpade)
                {
                    if (value >= maxBetting)
                    {
                        currentBettingSpade = maxBetting;
                    }
                    else
                    {
                      currentBettingSpade = value;
                    }
                    this.OnPropertyChanged("CurrentBettingSpade");
                }
            }
            get 
            {
                return currentBettingSpade;
            }
        }

        /// <summary>
        /// 当前红桃的投注量
        /// </summary>
        public double CurrentBettingHeart
        {
            set
            {
                if (value != currentBettingHeart)
                {
                    if (value >= maxBetting)
                    {
                        currentBettingHeart = maxBetting;
                    }
                    else
                    {
                        currentBettingHeart = value;
                    }
                    this.OnPropertyChanged("CurrentBettingHeart");
                }
            }
            get
            {
                return currentBettingHeart;
            }
        }

        /// <summary>
        /// 当前梅花的投注量
        /// </summary>
        public double CurrentBettingClub
        {
            set
            {
                if (value != currentBettingClub)
                {
                    if (value >= maxBetting)
                    {
                        currentBettingClub = maxBetting;
                    }
                    else
                    {
                        currentBettingClub = value;
                    }
                    this.OnPropertyChanged("CurrentBettingClub");
                }
            }
            get
            {
                return currentBettingClub;
            }
        }

        /// <summary>
        /// 当前方块的投注量
        /// </summary>
        public double CurrentBettingDiamond
        {
            set
            {
                if (value != currentBettingDiamond)
                {
                    if (value >= maxBetting)
                    {
                        currentBettingDiamond = maxBetting;
                    }
                    else
                    {
                        currentBettingDiamond = value;
                    }
                    this.OnPropertyChanged("CurrentBettingDiamond");
                }
            }
            get
            {
                return currentBettingDiamond;
            }
        }

        /// <summary>
        /// 当前王的投注量
        /// </summary>
        public double CurrentBettingKing
        {
            set
            {
                if (value != currentBettingKing)
                {
                    if (value >= maxBetting)
                    {
                        currentBettingKing = maxBetting;
                    }
                    else
                    {
                        currentBettingKing = value;
                    }

                    this.OnPropertyChanged("CurrentBettingKing");
                }
            }
            get
            {
                return currentBettingKing;
            }
        }

        /// <summary>
        /// 当前轮总共开黑桃的数量
        /// </summary>
        public int CurrentChapterCountOfSpade 
        {
            set
            {
                if (value != currentChapterCountOfSpade)
                {
                    currentChapterCountOfSpade = value;
                    this.OnPropertyChanged("CurrentChapterCountOfSpade");
                }
            }
            get
            {
                return currentChapterCountOfSpade;
            }

        }
        /// <summary>
        /// 当前轮总共开红桃的数量
        /// </summary>
        public int CurrentChapterCountOfHeart
        {
            set
            {
                if (value != currentChapterCountOfHeart)
                {
                    currentChapterCountOfHeart = value;
                    this.OnPropertyChanged("CurrentChapterCountOfHeart");
                }
            }
            get
            {
                return currentChapterCountOfHeart;
            }

        }
        /// <summary>
        /// 当前轮总共开梅花的数量
        /// </summary>
        public int CurrentChapterCountOfClub
        {
            set
            {
                if (value != currentChapterCountOfClub)
                {
                    currentChapterCountOfClub = value;
                    this.OnPropertyChanged("CurrentChapterCountOfClub");
                }
            }
            get
            {
                return currentChapterCountOfClub;
            }
        }
        /// <summary>
        /// 当前轮总共开方块的数量
        /// </summary>
        public int CurrentChapterCountOfDiamond
        {
            set
            {
                if (value != currentChapterCountOfDiamond)
                {
                    currentChapterCountOfDiamond = value;
                    this.OnPropertyChanged("CurrentChapterCountOfDiamond");
                }
            }
            get
            {
                return currentChapterCountOfDiamond;
            }
        }
        /// <summary>
        /// 当前轮总共开王的数量
        /// </summary>
        public int CurrentChapterCountOfKing
        {
            set
            {
                if (value != currentChapterCountOfKing)
                {
                    currentChapterCountOfKing = value;
                    this.OnPropertyChanged("CurrentChapterCountOfKing");
                }
            }
            get
            {
                return currentChapterCountOfKing;
            }
        }
       
        /// <summary>
        /// 当前轮已经开奖的牌局信息
        /// </summary>
        public ObservableCollection<GameRoundInfo> GameRoundInfos
        {
            set 
            {
              if(value != gameRoundInfos)
              {
                  gameRoundInfos = value;
                  this.OnPropertyChanged("GameRoundInfos");
              }
            }
            get
            {
                return gameRoundInfos;
            }

        }

        /// <summary>
        /// 开奖剩余时间(秒)
        /// </summary>
        public int? NextLeftTime
        {
            set
            {
                if (value != nextLeftTime)
                {
                    if(value < 0)
                    {
                        nextLeftTime = 0;
                    }
                    else
                    {
                       nextLeftTime = value;
                    }
                    this.OnPropertyChanged("NextLeftTime");
                }
            }
            get
            {
                return nextLeftTime;
            }
        }
        
        /// <summary>
        /// 投注黑桃的命令
        /// </summary>
        public UniversalCommand BettingSpadeCommand { set; get; }

        /// <summary>
        /// 投注红桃的命令
        /// </summary>
        public UniversalCommand BettingHeartCommand { set; get; }

        /// <summary>
        /// 投注梅花的命令
        /// </summary>
        public UniversalCommand BettingClubCommand { set; get; }

        /// <summary>
        /// 投注方块的命令
        /// </summary>
        public UniversalCommand BettingDiamondCommand { set; get; }

        /// <summary>
        /// 投注王的命令
        /// </summary>
        public UniversalCommand BettingKingCommand { set; get; }

        /// <summary>
        /// 当前是否自动投注黑桃
        /// </summary>
        public bool AutoBettingSpade
        {
            set
            {
                if (value != autoBettingSpade)
                {
                    autoBettingSpade = value;
                    this.OnPropertyChanged("AutoBettingSpade");
                }
            }
            get
            {
                return autoBettingSpade;
            }
        }
        /// <summary>
        /// 当前是否自动投注红桃
        /// </summary>
        public bool AutoBettingHeart
        {
            set
            {
                if (value != autoBettingHeart)
                {
                    autoBettingHeart = value;
                    this.OnPropertyChanged("AutoBettingHeart");
                }
            }
            get
            {
                return autoBettingHeart;
            }
        }
        /// <summary>
        /// 当前是否自动投注梅花
        /// </summary>
        public bool AutoBettingClub
        {
            set
            {
                if (value != autoBettingClub)
                {
                    autoBettingClub = value;
                    this.OnPropertyChanged("AutoBettingClub");
                }
            }
            get
            {
                return autoBettingClub;
            }
        }
        /// <summary>
        /// 当前是否自动投注方块
        /// </summary>
        public bool AutoBettingDiamond
        {
            set
            {
                if (value != autoBettingDiamond)
                {
                    autoBettingDiamond = value;
                    this.OnPropertyChanged("AutoBettingDiamond");
                }
            }
            get
            {
                return autoBettingDiamond;
            }
        }
        /// <summary>
        /// 当前是否自动投注王
        /// </summary>
        public bool AutoBettingKing
        {
            set
            {
                if (value != autoBettingKing)
                {
                    autoBettingKing = value;
                    this.OnPropertyChanged("AutoBettingKing");
                }
            }
            get
            {
                return autoBettingKing;
            }
        }

        #endregion

    

        public GameViewModel() :base(Page.游戏主页.ToString())
        { 
            try
            {
                this.GoldsDisplay = "当前余额:0";
                this.PropertyChanged += (sender, args) => {
                   if(args.PropertyName == "Golds")
                   {
                       this.GoldsDisplay = "当前余额:" + this.Golds;
                   }
                };

                gameClient.BettingCompleted += WrapEventHandler<BettingCompletedEventArgs>(BettingCompleted);
                gameClient.GetCurrentGameInfoCompleted += WrapEventHandler<GetCurrentGameInfoCompletedEventArgs>(GetCurrentGameInfoCompleted);
                gameClient.GetCurrentBettingUsersInfoCompleted += WrapEventHandler<GetCurrentBettingUsersInfoCompletedEventArgs>(GetCurrentBettingUsersInfoCompleted);

                sbBetting = new Storyboard();
                sbBetting.Duration = new System.Windows.Duration(new TimeSpan(0, 0, submitBettingSpan));
                sbBetting.Completed += SubmitBetting;
                sbBetting.Begin();
             
                sbTime = new Storyboard();
                sbTime.Duration = new System.Windows.Duration(new TimeSpan(0, 0, 1));
                sbTime.Completed += sbTime_Completed;
                sbTime.Begin();

                autoBetting = new Storyboard();
                autoBetting.Duration = new System.Windows.Duration(new TimeSpan(0,0,0,0,MinBettingSpan));
                autoBetting.Completed += autoBetting_Completed;
                autoBetting.Begin();

                GameRoundInfos = new ObservableCollection<GameRoundInfo>();
                CurrentBettingUserInfos = new ObservableCollection<CurrentBettingUserInfo>();
                this.BettingSpadeCommand = new UniversalCommand((x) => {
                    if (AutoBettingSpade) return;
                    this.AddBetting(PokerColor.黑桃);
                });

                this.BettingHeartCommand = new UniversalCommand((x) =>
                {
                    if (AutoBettingHeart) return;
                    this.AddBetting(PokerColor.红桃);
                });
                this.BettingClubCommand = new UniversalCommand((x) =>
                {
                    if (AutoBettingClub) return;
                    this.AddBetting(PokerColor.梅花);
                });
                this.BettingDiamondCommand = new UniversalCommand((x) =>
                {
                    if (AutoBettingDiamond) return;
                    this.AddBetting(PokerColor.方块);
                });
                this.BettingKingCommand = new UniversalCommand((x) =>
                {
                    if (AutoBettingKing) return;
                    this.AddBetting(PokerColor.王);
                });

               Golds = DataManager.GetValue<AuthorExport>(DataKey.User_SelfInfo).Golds;
            }
            catch (Exception ex)
            {
                this.ShowError(ex.Message);
            }
           
        }

        void autoBetting_Completed(object sender, EventArgs e)
        {
            if(AutoBettingSpade)
            {
                this.AddBetting(PokerColor.黑桃);
            }
            if (AutoBettingHeart)
            {
                this.AddBetting(PokerColor.红桃);
            }
            if (AutoBettingClub)
            {
                this.AddBetting(PokerColor.梅花);
            }
            if (AutoBettingDiamond)
            {
                this.AddBetting(PokerColor.方块);
            }
            if (AutoBettingKing)
            {
                this.AddBetting(PokerColor.王);
            }
            autoBetting.Begin();
        }



        /// <summary>
        /// 刷新当前显示的游戏信息
        /// </summary>
        /// <param name="game"></param>
        void RefreshDisplayGameInfo(GameChapterExport game)
        {
            if (game == null) return;
            if (CurrentChapterNumber == game.ChapterNumber 
                && CurrentRoundNumber == game.CurrentRoundNumber) return;
            CurrentChapterNumber = game.ChapterNumber;
            CurrentRoundNumber = game.CurrentRoundNumber;
            NextRoundNumber = game.NextRoundNumber;
            NextLotteryTime = game.NextRoundLotteryTime;
            GameRoundInfos.Clear();
            int countOfSpade = 0;
            int countOfHeart = 0;
            int countOfClub = 0;
            int countOfDiamond = 0;
            int countOfKing = 0;
            if (game.GameRounds != null)
            {
                game.GameRounds.ToList().ForEach(x => {
                    switch (x.PokerColor)
                    {
                        case PokerColor.黑桃: countOfSpade++;
                            break;
                        case PokerColor.红桃: countOfHeart++;
                            break;
                        case PokerColor.梅花: countOfClub++;
                            break;
                        case PokerColor.方块: countOfDiamond++;
                            break;
                        case PokerColor.王: countOfKing++;
                            break;
                        default:
                            break;
                    }
                    GameRoundInfos.Add(new GameRoundInfo(x));
                });
            }
            this.CurrentChapterCountOfSpade = countOfSpade;
            this.CurrentChapterCountOfHeart = countOfHeart;
            this.CurrentChapterCountOfClub = countOfClub;
            this.CurrentChapterCountOfDiamond = countOfDiamond;
            this.CurrentChapterCountOfKing = countOfKing;
            this.CurrentBettingKing = 0;
            this.CurrentBettingSpade = 0;
            this.CurrentBettingDiamond = 0;
            this.CurrentBettingClub = 0;
            this.CurrentBettingHeart = 0;
            this.AutoBettingSpade = false;
            this.AutoBettingHeart = false;
            this.AutoBettingClub = false;
            this.AutoBettingDiamond = false;
            this.AutoBettingKing = false;
            this.lastSuccessInfo = new BettingStateInfo();
            RefreshGolds();
        }

        bool isRefreshingGolds = false;

        /// <summary>
        /// 更新用户剩余的金币
        /// </summary>
        void RefreshGolds()
        {
            if (isRefreshingGolds) return;
            AuthorServiceClient asc = new AuthorServiceClient();
            asc.GetUserSelfInfoCompleted += WrapEventHandler<GetUserSelfInfoCompletedEventArgs>((s, args) => { 
                 if(args.Result.Success)
                 {
                     Golds = args.Result.Info.Golds;
                 }else
                 {
                     this.ShowError(args.Result.Error);
                 }
                 isRefreshingGolds = false;
            });
            asc.GetUserSelfInfoAsync(new GetUserSelfInfoImport() { Token = DataManager.GetValue<string>(DataKey.Iworld_Token)});
            isRefreshingGolds = true;
        }

        GameState currentGameState = GameState.未开始;

        /// <summary>
        /// 主要循环线程处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void sbTime_Completed(object sender, EventArgs e)
        {
             if(latestGameInfo != null)
             {
                 DateTime now = DateTime.Now;
                 //如果游戏正在开奖
                 if ((latestGameInfo.Status == GameChapterStatus.正在开奖 ||
                     latestGameInfo.Status == GameChapterStatus.开奖结束))
                 {
                     RefreshDisplayGameInfo(latestGameInfo);
                     DateTime nextTime = (DateTime)NextLotteryTime;
                     TimeSpan sp = nextTime - now;
                     this.NextLeftTime = (int)sp.TotalSeconds;
                     SettingOfGameExport sge = DataManager.GetValue<SettingOfGameExport>(DataKey.SettingOfGame);
                     currentGameState = GameState.正常投注;
                     if (sge != null)
                     {
                         int cloTime = sge.ClosureSingleTime;
                         if (NextLeftTime <= cloTime + 1)
                         {
                             this.SubmitBetting(null,null);
                         }
                         if (NextLeftTime <= cloTime)
                         {
                             currentGameState = GameState.封单;
                         }
                     }
                     TimeDisplay = "距下局开奖时间还剩下:" + NextLeftTime + "秒";
                     if(NextLeftTime <= 0)
                     {
                         RefreshGameInfo();
                     }
                     RefreshCurrentBettingUserInfos();
                 }
                 ///当前没有游戏正在开奖(牌轮之间的休息时间)
                 else if (latestGameInfo.ActiveTime != null && latestGameInfo.Status == GameChapterStatus.从未开奖)
                 {
                     currentGameState = GameState.未开始;
                     GameChapterExport lastGame = latestGameInfo.LastGame;
                     if (lastGame != null)
                     {
                       RefreshDisplayGameInfo(lastGame);
                     }
                     DateTime activeTime = (DateTime)latestGameInfo.ActiveTime;
                     NextLotteryTime = null;
                     NextLeftTime = null;
                     int nextChapter = ((int)((activeTime - now).TotalSeconds));
                     if (nextChapter <= 0)
                     {
                         RefreshGameInfo();
                     }
                     TimeDisplay = "本轮牌已经开奖结束,距离下轮牌开始还有:" + nextChapter + "秒";
                 }
             }
             else
             {
                 this.RefreshGameInfo();
             }
             sbTime.Begin();
        }

        bool isRefreshingCurrentBettingUserInfos = false;


        void RefreshCurrentBettingUserInfos()
        {
            if (isRefreshingCurrentBettingUserInfos) return;
            this.gameClient.GetCurrentBettingUsersInfoAsync(new GetCurrentBettingUsersInfoImport() { Token = DataManager.GetValue<string>(DataKey.Iworld_Token) });
            isRefreshingCurrentBettingUserInfos = true;
        }


        void GetCurrentBettingUsersInfoCompleted(object sender, GetCurrentBettingUsersInfoCompletedEventArgs e)
        {
            isRefreshingCurrentBettingUserInfos = false;
            if (e.Result.Success)
            {
                this.CurrentBettingUserInfos.Clear();
                e.Result.List.ToList().ForEach(x =>
                {
                    this.CurrentBettingUserInfos.Add(new CurrentBettingUserInfo(x));
                });
            }
            else
            {
                this.ShowError(e.Result.Error);
            }
        }


        /// <summary>
        /// 添加上分
        /// </summary>
        /// <param name="color"></param>
        void AddBetting(PokerColor color)
        {
            try
            {
                if (currentGameState != GameState.正常投注)
                {
                    return;
                }
                lock (this)
                {
                    if (Golds < bettingUnit)
                    {
                        return;
                    }
                    double oldBetting = 0;
                    double newBetting = 0;
                    switch (color)
                    {
                        case PokerColor.黑桃:
                            oldBetting = this.CurrentBettingSpade;
                            this.CurrentBettingSpade = this.CurrentBettingSpade + bettingUnit;
                            newBetting = this.CurrentBettingSpade;
                            break;
                        case PokerColor.红桃:
                            oldBetting = this.CurrentBettingHeart;
                            this.CurrentBettingHeart = this.CurrentBettingHeart + bettingUnit;
                            newBetting = this.CurrentBettingHeart;
                            break;
                        case PokerColor.梅花:
                            oldBetting = this.CurrentBettingClub;
                            this.CurrentBettingClub = this.CurrentBettingClub + bettingUnit;
                            newBetting = this.CurrentBettingClub;
                            break;
                        case PokerColor.方块:
                            oldBetting = this.CurrentBettingDiamond;
                            this.CurrentBettingDiamond = this.CurrentBettingDiamond + bettingUnit;
                            newBetting = this.CurrentBettingDiamond;
                            break;
                        case PokerColor.王:
                            oldBetting = this.CurrentBettingKing;
                            this.CurrentBettingKing = this.CurrentBettingKing + bettingUnit;
                            newBetting = this.CurrentBettingKing;
                            break;
                        default:
                            throw new Exception("出错了");
                    }
                    Golds = Golds - (newBetting - oldBetting);
                }

                TriggerBetting();
            }
            catch (Exception ex)
            {
                this.ShowError(ex.Message);
            }
        }

        /// <summary>
        /// 触发正在投注状态
        /// </summary>
        void TriggerBetting()
        {
            if (sbStopBetting != null)
            {
                sbStopBetting.Stop();
            }
            sbStopBetting = new Storyboard();
            sbStopBetting.Duration = new System.Windows.Duration(new TimeSpan(0, 0, 3));
            sbStopBetting.Completed += (sender, args) =>
            {
                isNeedSubmitBetting = false;
                sbStopBetting = null;
            };
            isNeedSubmitBetting = true;
            sbStopBetting.Begin();
        }


        bool isRefreshingGameInfo = false;
        DateTime? refreshGameInfoTime;

        void RefreshGameInfo()
        {
            if (isRefreshingGameInfo) return;
            gameClient.GetCurrentGameInfoAsync(new GetCurrentGameInfoImport() { Token = DataManager.GetValue<string>(DataKey.Iworld_Token)});
            isRefreshingGameInfo = true;
        }

        /// <summary>
        /// 获取游戏信息回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void GetCurrentGameInfoCompleted(object sender, GetCurrentGameInfoCompletedEventArgs e)
        {
           isRefreshingGameInfo = false;
           if(e.Result.Success)
           {
               latestGameInfo = e.Result.Info;
               refreshGameInfoTime = DateTime.Now;
           }
           else
           {
               this.ShowError(e.Result.Error);
           }
        }

        /// <summary>
        /// 投注回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BettingCompleted(object sender, BettingCompletedEventArgs e)
        {
            //提交的投注量
            BettingStateInfo bsi = (BettingStateInfo)e.UserState;
            if(e.Result.Success)
            {
                //成功的投注量
                BettingResultExport successBetting = e.Result.Info;
                lastSuccessInfo = new BettingStateInfo()
                {
                    Spade = successBetting.Spade,
                    Heart = successBetting.Heart,
                    Club = successBetting.Club,
                    Diamond = successBetting.Diamond,
                    King = successBetting.King,
                    GameRoundNum = successBetting.GameRoundNum
                };
                if(bsi.GameRoundNum == successBetting.GameRoundNum)
                {
                    if(successBetting.Spade != bsi.Spade)
                    {
                        CurrentBettingSpade = successBetting.Spade;
                    }
                    if (successBetting.Heart != bsi.Heart)
                    {
                        CurrentBettingHeart = successBetting.Heart;
                    }
                    if (successBetting.Club != bsi.Club)
                    {
                        CurrentBettingClub = successBetting.Club;
                    }
                    if (successBetting.Diamond != bsi.Diamond)
                    {
                        CurrentBettingDiamond = successBetting.Diamond;
                    }
                    if (successBetting.King != bsi.King)
                    {
                        CurrentBettingKing = successBetting.King;
                    }
                }
            }
            else
            {
                CurrentBettingSpade = lastSuccessInfo.Spade;
                CurrentBettingHeart = lastSuccessInfo.Heart;
                CurrentBettingClub = lastSuccessInfo.Club;
                CurrentBettingDiamond = lastSuccessInfo.Diamond;
                CurrentBettingKing = lastSuccessInfo.King;
            }
            isBetting = false;
        }

        bool isBetting = false;

        BettingStateInfo lastSuccessInfo = new BettingStateInfo();

        /// <summary>
        /// 提交投注到后台
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void SubmitBetting(object sender, EventArgs e)
        {
            if (!isBetting && isNeedSubmitBetting && currentGameState == GameState.正常投注)
            {
                    gameClient.BettingAsync(
                    new BettingImport()
                    {
                        Token = DataManager.GetValue<string>(DataKey.Iworld_Token),
                        Spade = this.CurrentBettingSpade,
                        Heart = this.CurrentBettingHeart,
                        Club = this.CurrentBettingClub,
                        Diamond = this.CurrentBettingDiamond,
                        King = this.CurrentBettingKing,
                        GameRoundNum = (int)NextRoundNumber
                    }, new BettingStateInfo()
                    {
                        Spade = this.CurrentBettingSpade,
                        Heart = this.CurrentBettingHeart,
                        Club = this.CurrentBettingClub,
                        Diamond = this.CurrentBettingDiamond,
                        King = this.CurrentBettingKing,
                        GameRoundNum = (int)NextRoundNumber
                    });
                    isBetting = true;
            }
            sbBetting.Begin();
        } 
    }

    /// <summary>
    /// 牌局的信息
    /// </summary>
    public class GameRoundInfo : ModelBase
    {
        public string Text { set; get; }

        public GameRoundInfo(GameRoundExport gre)
        {
           PokerNumber number =  gre.PokerNumber;
           Text = gre.PokerColor.ToString() + gre.PokerNumber.ToString();
        }
    }

    /// <summary>
    /// 投注缓存状态信息
    /// </summary>
    public class BettingStateInfo
    {
        /// <summary>
        /// 投注牌局号
        /// </summary>
        public int GameRoundNum { set; get; }
        /// <summary>
        /// 黑桃的投注量
        /// </summary>
        public double Spade { set; get; }
        /// <summary>
        /// 红桃的投注量
        /// </summary>
        public double Heart { set; get; }
        /// <summary>
        /// 梅花的投注量
        /// </summary>
        public double Club { set; get; }
        /// <summary>
        /// 方块的投注量
        /// </summary>
        public double Diamond { set; get; }
        /// <summary>
        /// 王的投注量
        /// </summary>
        public double King { set; get; }
    }

    /// <summary>
    /// 当前实时用户的投注信息
    /// </summary>
    public class CurrentBettingUserInfo
    {

        public CurrentBettingUserInfo(CurrentBettingUsersInfoExport u)
        {
            this.Golds = u.Golds;
            this.Username = u.Username;
            this.GameRoundNum = u.GameRoundNum;
            this.Spade = u.Spade;
            this.Heart = u.Heart;
            this.Club = u.Club;
            this.Diamond = u.Diamond;
            this.King = u.King;
        }

        /// <summary>
        /// 用户剩余金币
        /// </summary>
      
        public double Golds { set; get; }

        /// <summary>
        /// 用户名称
        /// </summary>
       
        public string Username { set; get; }

        /// <summary>
        /// 投注牌局号
        /// </summary>
      
        public int GameRoundNum { set; get; }

        /// <summary>
        /// 黑桃的成功投注量
        /// </summary>
       
        public double Spade { set; get; }

        /// <summary>
        /// 红桃的成功投注量
        /// </summary>
       
        public double Heart { set; get; }

        /// <summary>
        /// 梅花的成功投注量
        /// </summary>
      
        public double Club { set; get; }

        /// <summary>
        /// 方块的成功投注量
        /// </summary>
       
        public double Diamond { set; get; }

        /// <summary>
        /// 王的成功投注量
        /// </summary>
       
        public double King { set; get; }
    }

    public enum GameState
    {
        未开始,正常投注,封单
    }
}
